import 'package:flutter/material.dart';
import 'package:shopping_group/modle/main/bloc/main_data_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';

import 'details_page.dart';

class CategoryPage extends StatefulWidget {
  final String title;
  final String typeId;
  const CategoryPage({Key key, this.title, this.typeId}) : super(key: key);
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  //listview的控制器
  ScrollController _scrollController = ScrollController();
  List<CommoSpec4AppRecordEntity> _list = [];
  Map<String, List<CommoSpec4AppRecordEntity>> _maplist = {};
  MainDataBloc _bloc;
  String _typeId;
  @override
  void initState() {
    super.initState();
    _typeId = this.widget.typeId;
    _initListener();
    _bloc = MainDataBloc();
    _bloc.initCommSpecData.add(_typeId);
  }

  _initListener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _bloc.moreDate.add(_scrollController);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, this.widget.title),
      body: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colours.title_white,
        ),
        child: _categoryView(),
      ),
    );
  }

  Widget _categoryView() {
    return Container(
      margin: const EdgeInsets.only(top: 8, left: 8, right: 8),
      decoration: BoxDecoration(
          border: Border.all(color: Colours.title_white, width: 1.0),
          borderRadius: BorderRadius.circular(15.0),
          color: Colours.title_white),
      child: _showlistView(),
    );
  }

  Widget _showlistView() {
    return StreamBuilder(
      stream: _bloc.sendCommSpecData,
      initialData: null == _maplist[_typeId] ? _list : _maplist[_typeId],
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _maplist[_typeId] = [];

          if (ObjectUtil.isEmptyList(object)) {
            _maplist[_typeId] = [];
          } else {
            for (var item in object) {
              _maplist[_typeId].add(item);
            }
          }
        }
        int count = null == _maplist[_typeId] ? 0 : _maplist[_typeId].length;
        if (0 != count) {
          return Container(
            decoration: new BoxDecoration(
              color: Colors.white,
            ),
            child: RefreshIndicator(
              onRefresh: _pullToRefresh,
              child: ListView.builder(
                controller: _scrollController,
                shrinkWrap: true,
                padding: const EdgeInsets.only(top: 4),
                itemCount: _maplist[_typeId].length,
                itemBuilder: buildItem,
              ),
            ),
          );
        } else {
          return Container(
            alignment: Alignment.center,
            child: WidgetUtils.emptyView(
              contexts,
            ),
          );
        }
      },
    );
  }

  Future _pullToRefresh() async {
    _maplist[_typeId]?.clear();
    _bloc.refreshDate.add(_typeId);
    return null;
  }

  //ListView的Item
  Widget buildItem(BuildContext context, int index) {
    return Container(
      // margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: GestureDetector(
          onTap: () {
            // if (!BaseConstant.isLogin) {
            //   RouteUtil.goView(PageConstance.LOGIN_PAGE);
            //   return;
            // }
            // BaseConstant.openShopId = _maplist[_typeId][index].id;
            // RouteUtil.goView(PageConstance.DETAILS_PAGE);
            RouteUtil.goParameter(DetailsPage(id: _maplist[_typeId][index].id));
          },
          child: _xunchaItem(_maplist[_typeId][index])),
    );
  }

  Widget _xunchaItem(CommoSpec4AppRecordEntity entity) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 90.0,
              width: 90.0,
              margin: const EdgeInsets.all(2.0),
              child: FadeInImage.assetNetwork(
                image: entity.imgUrl,
                placeholder: 'images/picture_loading.png',
                fit: BoxFit.contain,
              ),
            ),
            flex: 2,
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  WidgetUtils.getTextMaxLinesView(
                      entity.name, Colours.text_2222, Dimens.FONT_SIZE_14,
                      maxLines: 3),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 0),
                        child: Row(
                          children: <Widget>[
                            WidgetUtils.getTextColorView('¥${entity.outPrice}',
                                Colours.text_2222, Dimens.FONT_SIZE_16),
                            SizedBox(
                              width: 4,
                            ),
                            WidgetUtils.getTextColorView('¥${entity.outPrice}',
                                Colours.gray_99, Dimens.FONT_SIZE_16,
                                decoration: TextDecoration.lineThrough,
                                decorationColor: Colours.gray_66),
                          ],
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.only(top: 4),
                        child: WidgetUtils.getTextColorView(
                            '已售 ${entity.hadShopCt} 件',
                            Colours.text_2222,
                            Dimens.FONT_SIZE_12,
                            overflow: TextOverflow.clip),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }
}
